﻿using System;
using System.Collections.Generic;
using System.Text;
using GroupChat2013.Logic.Interface;
using System.Threading;

namespace GroupChat2013.Logic
{
    /// <summary>
    /// 聊天界面管理类
    /// </summary>
    public class ChatManager
    {
        private Dictionary<string, IChat> m_ChatDic;

        private static object locker = new object();

        /// <summary>
        /// 有聊天窗体打开后通知
        /// </summary>
        public event Action<string> NoticeChatOpenedHandler;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ChatManager()
        {
            m_ChatDic = new Dictionary<string, IChat>() { };
        }

        /// <summary>
        /// 访问器
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IChat this[string key]
        {
            get
            {
                if (m_ChatDic.ContainsKey(key))
                    return m_ChatDic[key];
                else
                    return null;
            }
        }

        /// <summary>
        /// 添加项
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public void AddChat(string key, IChat value)
        {
            lock (locker)
            {
                m_ChatDic.Add(key, value);
            }
        }

        /// <summary>
        /// 删除某个项
        /// </summary>
        /// <param name="key">键</param>
        public void RemoveChat(string key)
        {
            lock (locker)
            {
                if (m_ChatDic.ContainsKey(key))
                    m_ChatDic.Remove(key);
            }
        }

        /// <summary>
        /// 获取聊天窗体数组
        /// </summary>
        /// <returns></returns>
        public IEnumerable<IChat> GetChats()
        {
            return m_ChatDic.Values;
        }

        /// <summary>
        /// 是否包含某个项
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public bool ContainsKey(string key)
        {
            return m_ChatDic.ContainsKey(key);
        }

        /// <summary>
        /// 某个聊天窗体已经打开
        /// </summary>
        /// <param name="key">键</param>
        public void NoticeChatOpened(string key)
        {
            if (NoticeChatOpenedHandler != null)
                NoticeChatOpenedHandler(key);
        }
    }
}
